import React, { memo, useEffect, useState } from 'react'
import { EyeInvisibleOutlined, EyeOutlined } from '@ant-design/icons'
import login from './index.module.css'

import carIcon from 'asserts/images/login/car.png'

import { userLoginApi, queryUserInfoApi } from 'api/login.js'
import { useNavigate } from 'react-router-dom'

import { useNotification } from 'utils/notificationContext.js'

import { leftLinks } from 'service/local-data'

const LoginForm = memo(() => {
  const [username, setUsername] = useState('')
  const [password, setPassword] = useState('')
  const [rememberPassword, setRememberPassword] = useState(false)
  const [isSee, setIsSee] = useState(false)
  const navigate = useNavigate()
  
  const { openNotification } = useNotification()

  useEffect(() => {
    const storedUsername = localStorage.getItem("username");
    const storedPassword = localStorage.getItem("password");
    if (storedUsername && storedPassword) {
      setUsername(storedUsername)
      setPassword(storedPassword)
      setRememberPassword(true)
    }
  },[])

  const handleInputChange = (e) => {
    const { name, value } = e.target;
    if (name === 'username') {
      setUsername(value)
    }else if(name === 'password'){
      setPassword(value)
    }
  };

  const handleRememberPasswordChange = (e) => {
    const { checked } = e.target;
    setRememberPassword(checked)
  };

  const handleSubmit = (e) => {
    e.preventDefault();
    if (!username) {
      openNotification('账号不能为空！', 'warning')
      return
    }else if (!password) {
      openNotification('密码不能为空！', 'warning')
      return
    }
    // 处理登录逻辑
    if (rememberPassword) {
      localStorage.setItem("password", password);
    } else {
      localStorage.removeItem("password");
    }
    // const formData = new FormData()
    // formData.append('username', username)
    // formData.append('password', password)
    
    // userLoginApi(formData).then(loginRes => {
    userLoginApi({account: username, password}).then(loginRes => {
      console.log(loginRes);
      if (loginRes.code === 200) {
        const token = loginRes.token
        localStorage.setItem("userToken", token); //缓存token
        localStorage.setItem("login_password", password);
        queryUserInfoApi().then(userInfoRes => {
          console.log(userInfoRes);
          if (userInfoRes.code === 200) {
            setTimeout(() => {
              const userInfo = userInfoRes.user
              let menu = [];
              if (userInfoRes?.permissions[0] === "*:*:*") {
                menu = leftLinks
              }else{
                // userInfoRes?.permissions?.forEach(item1 => {
                //   leftLinks.forEach(item2 => {
                //     if (item1.name === item2.title) {
                //       menu.push({
                //         title: item2.title,
                //         link: item2.link
                //       });
                //     }
                //   });
                // });
                userInfoRes?.permissions?.forEach(item1 => {
                  leftLinks.forEach(item2 => {
                    if (item1 === item2.type) {
                      menu.push(item2);
                    }
                  });
                });
                // menu根据sort升序排列
                menu.sort((a, b) => a.sort - b.sort);
              }
              console.log(menu);
              
              localStorage.setItem("menu", JSON.stringify(menu));  //缓存用户菜单
              localStorage.setItem("userInfo", JSON.stringify({...userInfo, roles: userInfoRes.roles}));  //缓存用户信息
              localStorage.setItem("account_status", userInfo.status);  //缓存用户信息
              if (menu.length) {
                if (userInfo.status === 1) {
                  openNotification('登录成功~', 'success')
                  navigate('/layout', {replace: true})
                }else if (userInfo.status === 0){
                  openNotification('您登录的账号暂未启用，请联系管理员~', 'warning')
                }
              }else {
                openNotification('暂未为您分配菜单权限，请联系管理员~', 'warning')
              }
            }, 2000)
          }
        }).catch(userInfoErr => {
          openNotification('获取用户信息失败', 'fail')
          console.log(userInfoErr);
        })
      }else{
        openNotification(loginRes.msg, 'fail')
      }
    }).catch(loginErr => {
      openNotification('登录失败', 'fail')
      console.log(loginErr);
    })

  };

  return (
    <div className={login.container}>
      <div className={login.container_left}>
        <div className={login.left_img}>
          <img src={carIcon} alt="" />
        </div>
      </div>
      <div className={login.container_left}>
        <div className={login.container_wrap}>
          <div className={login.tips}>欢迎登录</div>
          <div className={login.title}>Track 小车管理平台</div>
          <form onSubmit={handleSubmit} >
            <div className={login.form_item}>
              <input
                type="text"
                name="username"
                value={username}
                autoComplete='off'
                placeholder='请输入账号'
                onChange={handleInputChange}
              />
            </div>
            <div className={login.form_item}>
              <input
                type={isSee ? 'text' : 'password'}
                name="password"
                value={password}
                autoComplete='off'
                placeholder='请输入密码'
                onChange={handleInputChange}
              />
              {
                isSee ? 
                  <div className={login.see_pwd} onClick={() => setIsSee(false)}>
                    <EyeOutlined />
                  </div>
                :
                  <div className={login.see_pwd} onClick={() => setIsSee(true)}>
                    <EyeInvisibleOutlined />
                  </div>
              }
            </div>
            <div className={login.password_wrap}>
              <div className={login.remember_pwd}>
                <input
                  className={login.remember_checkbox}
                  type="checkbox"
                  name="rememberPassword"
                  checked={rememberPassword}
                  onChange={handleRememberPasswordChange}
                />
                <span>记住密码</span>
              </div>
              <div className={login.forget_pwd}>
                <span>忘记密码</span>
              </div>
            </div>
            <button className={login.submit_btn} type="submit">登录</button>
            <div className={login.register}>
              <span>还没有账号？</span>
              <span className={login.register_link} onClick={() => navigate('/register', {replace: true})}>立即注册</span>
            </div>
          </form>
        </div>
      </div>
    </div>
  );
})

export default LoginForm

